package cn.shadow.utils;

import com.google.protobuf.ByteString;

import java.util.Arrays;

public class StringHolder {
    private String value;
    private byte[] valueBytes;
    private ByteString valueByteString;

    public StringHolder() {
        this.value = "";
        this.valueBytes = Empty.BYTE_ARRAY;
        this.valueByteString = ByteString.EMPTY;
    }

    public StringHolder(String name) {
        onValueChanged(name);
    }

    public StringHolder(byte[] nameBytes) {
        onValueBytesChanged(nameBytes);
    }

    public StringHolder(ByteString nameByteString) {
        onValueByteStringChanged(nameByteString);
    }

    public String get() {
        return value;
    }

    public byte[] getBytes() {
        return valueBytes;
    }

    public ByteString getByteString() {
        return valueByteString;
    }

    public boolean onValueChanged(String string) {
        if (string.equals(value)) {
            return false;
        }

        this.value = string;
        this.valueBytes = StringEncoder.encode(string);
        this.valueByteString = ByteString.copyFrom(valueBytes);

        return true;
    }

    public boolean onValueBytesChanged(byte[] nameBytes) {
        if (Arrays.equals(this.valueBytes, nameBytes)) {
            return false;
        }

        this.value = StringEncoder.encode(nameBytes);
        this.valueBytes = nameBytes;
        this.valueByteString = ByteString.copyFrom(nameBytes);

        return true;
    }

    public boolean onValueByteStringChanged(ByteString nameByteString) {
        if (nameByteString.equals(valueByteString)) {
            return false;
        }

        this.valueBytes = nameByteString.toByteArray();
        this.value = StringEncoder.encode(valueBytes);
        this.valueByteString = nameByteString;

        return true;
    }
}
